% Matlab Code for replication of "Optimal Debt Maturity and Firm Investment"
% by J. Jungherr and I. Schott, September 2020
  
function solve_model(PARMS)  

% Setup
VAL.period              = 1;
VAL.HISTORY             = cell(1,1);

setup_matrices % Creates empty matrices

% Solve period T-1
solve_T_1
 
simulate_V

% Solve period T-x
for oo = 1:599
    solve_T_x
end

%% Compute moments

% Compute stationary distribution
stationary_dist

% Compute model moments
model_moments


%% Collect output for Table 6

% 1) Average firm leverage
Tab6_LTDfr.meanlev          = 100*modelmoms.leverage.mean;
% 2) Average default rate
Tab6_LTDfr.defrate          = 100*moment.defrate;
% 3) Average issuance-weighted credit spread
Tab6_LTDfr.meanspread       = 100*moment.iwspread;
% 4) Average LTD share
Tab6_LTDfr.LTDshare         = 100*modelmoms.ltd_share.mean;

% Real variables
Tab6_LTDfr.AvgK             = moment.AvgK;
Tab6_LTDfr.AggK             = moment.AggK;
Tab6_LTDfr.GDP              = moment.GDP;
Tab6_LTDfr.Cons             = moment.Cons;
    
% Save model output
filename            = sprintf('%s%s','Tab6_LTDfr','.mat');
fullname            = fullfile(PARMS.tabfolder, filename);
save(fullname,'Tab6_LTDfr'); % save as .mat file



